package com.mzj.saas.jobs.bill.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 合同租金/押金未支付处理
 */

@Service
public class HouseContractPayTimeService {
    private static Logger log = LoggerFactory.getLogger(HouseContractPayTimeService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public String work() throws Exception {

        try{
            log.info("HouseContractPayTimeService 合同租金/押金未支付处理  start");

            //定时扫描合同开始时间与企业租金/押金时效设置的时间进行比对处理，
            // 如果当前时间超过有效期，将合同状态重置为：已过期
            //  status  '合同状态：0初稿 1待签约、2已签约待确认、3已确认待交租、4已交租待备案、5已备案履约中、6已到期待续约 7已续约 10已过期',

            String contractSQL = "select c.contract_nubmer,c.start_time ,h.org_id  from saas_house_contract c " +
                    "left join saas_house h on c.house_id=h.id where c.status in (0,1)  ";

            String contractPayTimeSQL = " select * from saas_house_contract_pay_time ";

            List<Map<String,Object>> contractList = jdbcTemplate.queryForList(contractSQL);

            List<Map<String,Object>> contractPayTimeList = jdbcTemplate.queryForList(contractPayTimeSQL);

            Date now = new Date();

            for(Map<String,Object> m : contractList){
                Long  orgId = (Long)m.get("org_id");
                for(Map<String,Object> map : contractPayTimeList){
                    if(orgId.equals(map.get("org_id"))){

                        int dayNum = daysBetween((Date)m.get("start_time"),now);
                        int time = (Integer) map.get("time");
                        if(dayNum > time){  //超过有效期
                            String updateSQL = "update saas_house_contract c set c.status=10 where c.contract_nubmer ='"+m.get("contract_nubmer")+"'";
                            jdbcTemplate.update(updateSQL);
                            break;
                        }

                    }
                }
            }

            log.info("HouseContractPayTimeService 合同租金/押金未支付处理  end");
        }catch (Exception e){
            log.error("合同租金/押金未支付处理异常  " + e.getMessage(),e);
        }

        return "SUCCESS";
    }

    /**
     * 计算两个日期相差多少天(by date)
     */
    public int daysBetween(Date date1, Date date2){
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);
        long time1 = cal.getTimeInMillis();
        cal.setTime(date2);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }



}
